package com.palmelf.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.log4j.Logger;
import org.palmelf.log.WebLogAppender;
import org.palmelf.service.PhontographService;
import org.palmelf.service.PhontographServiceImpl;

public class ImgMonitorThread extends BaseMonitorThread {
	private static Logger LOG = Logger.getLogger("ImgMonitorThread");

	@Override
	public String getImgprefix() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void executeRun() {
		PhontographService phontographService = new PhontographServiceImpl();

		int bytesum = 0;
		int byteread = 0;
		byte[] buffer = new byte[1444];

		File oldFile = new File(monitorPath);
		File newFile = new File(targetPath); // 目标文件夹
		if (!newFile.exists()) { // 如果存入的目标文件夹不存在，就创建一个文件夹
			newFile.mkdirs();
		}
		List<String> imgList = FileUtil.recursionGetFileDirectory(oldFile, fileType);

		for (String imgPath : imgList) {
			LOG.debug("imgList： ---------------------" + imgList);
			try {
				String imgName = System.currentTimeMillis() + ".jpg";
				File imgFile = new File(imgPath);
				InputStream inStream = new FileInputStream(imgFile); // 读入文件流路径
				FileOutputStream fs = new FileOutputStream(targetPath + "/" + imgName);// 写出文件流路径
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.flush();
				fs.close();
				phontographService.addPhontograph(imgName);
				imgFile.delete();// 删除文件

				WebLogAppender wla = new WebLogAppender();
				// 通知前台过来取数据
				wla.getWriter().append("访问成功！");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
